package flink_demo;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;


/**
 *
 * @author Spring_Hu
 * @date 2021/10/9
 */
public class Flink_demo01 {
    public static void main(String[] args) throws Exception {
        //flink 批处理

        ExecutionEnvironment en = ExecutionEnvironment.getExecutionEnvironment();


        DataSource<String> ds = en.readTextFile("test/word.txt");



        AggregateOperator<Tuple2<String, Long>> result = ds.flatMap(new FlatMapFunction<String, String>() {
            public void flatMap(String line, Collector<String> collector) throws Exception {
                for (String word : line.split(" ")) {
                    collector.collect(word);
                }
            }
        }).map(new MapFunction<String, Tuple2<String, Long>>() {
            public Tuple2<String, Long> map(String word) throws Exception {
                return Tuple2.of(word, 1L);
            }
        }).groupBy(0)
                .sum(1);


        result.print();
    }
}
